package com.example.volleytest.network;

import android.content.Context;
import android.graphics.Bitmap;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.Volley;

public class VolleyHelper {
    private static VolleyHelper instance;
    private static final Object lock = new Object();

    private RequestQueue requestQueue;
    private ImageLoader imageLoader;

    public static VolleyHelper getInstance() {
        synchronized (lock) {
            if (instance == null) {
                instance = new VolleyHelper();
            }
        }

        return instance;
    }

    private VolleyHelper() {
        requestQueue = null;
        imageLoader = null;
    }

    public void init(Context context) {
        requestQueue = Volley.newRequestQueue(context);// thread pool(4)
        imageLoader = new ImageLoader(requestQueue, new ComplexCache(0.5f));
    }

    public Request addRequest(Request request) {
        if (requestQueue != null) {
            return requestQueue.add(request);
        } else {
            return null;
        }
    }

    public void cancelAll(final Object tag) {
        if (requestQueue != null) {
            requestQueue.cancelAll(tag);
        }
    }

    public ImageContainer getImageContainer(String requestUrl, final ImageLoader.ImageListener listener) {
        if (imageLoader != null) {
            return imageLoader.get(requestUrl, listener);
        } else {
            return null;
        }
    }

    public ImageLoader getImageLoader() {
        return imageLoader;
    }
}
